<?php

namespace App\Http\Controllers;

use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Cache\Simple\RedisCache;


/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller{

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(Request $request){
//        try {
            $code = (string)$request->get('code','');
            $user_id = (int)$request->get('uid',0);
            $app = app('wechat.mini_program');
            $predis = app('redis')->connection()->client();
            $cache = new RedisCache($predis);
            $app->rebind('cache', $cache);
            $data = $app->auth->session($code);
            $user = Users::where('openid',$data['openid'])->first();
            if(!$user){
                //不存在创建新用户
                $user = Users::create([
                    'openid' => $data['openid'],
                    'password' => bcrypt($data['openid']),
                    'register_at' => Carbon::now(),
                    'login_at' => Carbon::now(),
                ]);
                //更新个人任务信息
//                Log::info('invite_friends-'.$user_id);
                if($user_id > 0){
                    $this->finishTask($user_id,'invite_friends',$user['id']); //新邀用户加任务记录
                }

            }
//            if($user_id > 0 && $user_id != $user['id']){
//                $this->finishTask($user_id,'shared_friends',$user['id']); //分享用户加任务记录
//            }
            if (auth()->attempt(['openid' => $data['openid'], 'password' => $data['openid']])) {
                //删除用户已存在的个人token
                DB::table('oauth_access_tokens')
                    ->where('user_id',$user['id'])
                    ->delete();
                $return['token'] = $user->createToken('大队长广告')->accessToken;
                $return['user']  = $user->toArray();
                return $this->returnJson(0,'',$return);
            }
            return $this->returnJson(1, '登录失败');
//        } catch (\Exception $e) {
//            return $this->returnJson(1, '登录失败');
//        }
    }


    /**
     * 刷新token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function refresh(Request $request){
        try {
            $refreshToken = $request->get('refresh_token','');
            if(empty($refreshToken)){
                return $this->returnJson(1, '参数错误');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.refresh'), [
                'refresh_token' => $refreshToken,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (RequestException $exception) {
            return $this->returnJson(1, '刷新失败');
        }
        //
        //
    }



}
